﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.IO;
using System.Collections;
using System.Net;
using System.Text;

public partial class Main_Reports_Accounts_LedgerDetails : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    string strSql = string.Empty;
    double dblDebit = 0;
    double dblCredit = 0;
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {
            //**************Set Minimum and maximum date calender Control********
            AccountSettings.setMinMaxDate(form1);
            //********************End **********
            _BindLedger();
            txtFromDate.Text = "04/01/" + Session["FINYEAR"].ToString();
            txtToDate.Text = "31/03/" + (Convert.ToInt32(Session["FINYEAR"].ToString()) + 1).ToString();
        }
    }
    private void _BindLedger()
    {
        strSql = "SELECT LID,LNAME FROM ACC_LEDMAST WHERE ALWSUB=0 ORDER BY LNAME";
        DataTable DTLedger = DU.getdata(strSql);
        if (DTLedger.Rows.Count > 0)
        {
            ddlLedger.DataSource = DTLedger;
            ddlLedger.DataTextField = "LNAME";
            ddlLedger.DataValueField = "LID";
            ddlLedger.DataBind();
            ddlLedger.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--Select Ledger--", "0"));
        }
    }
    private void _BindLedgerDetails(string strLID, string strFromDate, string strToDate)
    {
        if (strLID != string.Empty)
        {
            if (strFromDate != string.Empty && strToDate != string.Empty)
            {
                lblHeading.Text = "Ledger details of " + ddlLedger.SelectedItem.Text + " from " + Convert.ToDateTime(strFromDate).ToString("dd-MMM-yyyy") + " To " + Convert.ToDateTime(strToDate).ToString("dd-MMM-yyyy") + ".";
                string[] str = strFromDate.ToString().Split('/');
                strFromDate = str[1] + "/" + str[0] + "/" + str[2];
                str = strToDate.ToString().Split('/');
                strToDate = str[1] + "/" + str[0] + "/" + str[2];
                SqlParameter[] sparam ={
                                           new SqlParameter("@FromDate",strFromDate),
                                           new SqlParameter("@ToDate",strToDate),
                                           new SqlParameter("@LedgerID",strLID),
                                           new SqlParameter("@IncludeOptionalVoucher","1")
                                       };
                DataTable DTLedgerDetails = DU.getdatausingprocedure("USP_ACC_GetGeneralLedgerVouchers", sparam);
                if (DTLedgerDetails.Rows.Count == 0)
                {
                    DataRow DTRow = DTLedgerDetails.NewRow();
                    for (int i = 0; i < DTLedgerDetails.Columns.Count; i++)
                    {

                        if (i == 1)
                        {

                        }
                        else
                        {
                            DTRow[i] = "0";
                        }
                    }
                    DTLedgerDetails.Rows.Add(DTRow);
                    grdDisplay.DataSource = DTLedgerDetails;
                    grdDisplay.DataBind();
                }
                else
                {
                    DataView DVLedger = DTLedgerDetails.DefaultView;
                    DVLedger.RowFilter = "Particulars=SelectedLedger";
                    grdDisplay.DataSource = DVLedger;
                    grdDisplay.DataBind();
                }
            }
        }
    }
    protected void btnShow_Click(object sender, EventArgs e)
    {
        _BindLedgerDetails(ddlLedger.SelectedValue, txtFromDate.Text, txtToDate.Text);       
    }
    protected void grdDisplay_RowDataBound(object sender, GridViewRowEventArgs  e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            string strTranId = grdDisplay.DataKeys[e.Row.RowIndex].Values["TransactionID"].ToString();
            if (strTranId == "0")
            {
                e.Row.Cells[0].Attributes.Add("colspan", "6");
                e.Row.Cells.RemoveAt(5);
                e.Row.Cells.RemoveAt(4);
                e.Row.Cells.RemoveAt(3);
                e.Row.Cells.RemoveAt(2);
                e.Row.Cells.RemoveAt(1);
                e.Row.Cells[0].Text = "No Transactions Made During this Period";
                e.Row.Cells[0].Style.Add("color", "red");
                e.Row.Cells[0].Style.Add("text-align", "center");
            }
            else
            {
                //**************** Particulars***********//
                strSql = "SELECT ACC_VOUDETAILS.LID,ACC_LEDMAST.LNAME FROM ACC_LEDMAST INNER JOIN ACC_VOUDETAILS ON ";
                strSql += " ACC_LEDMAST.LID=ACC_VOUDETAILS.LID WHERE ACC_VOUDETAILS.TRANID='" + strTranId + "' AND ACC_VOUDETAILS.LID<>'" + ddlLedger.SelectedValue + "'";
                DataTable DT = DU.getdata(strSql);
                if (DT.Rows.Count > 0)
                {
                    if (DT.Rows.Count > 1)
                    {
                        e.Row.Cells[1].Text = "Multiple Entries";
                    }
                    else
                    {
                        e.Row.Cells[1].Text = DT.Rows[0]["LNAME"].ToString();
                    }
                }
                //***************End Particular**********//
                //***************Display Format and get total ****//
                Label lblDebit = (Label)e.Row.FindControl("lblDebit");
                Label lblCredit = (Label)e.Row.FindControl("lblCredit");
                Label lblBalance = (Label)e.Row.FindControl("lblBalance");
                HiddenField hidDebit = (HiddenField)e.Row.FindControl("hidDebit");
                HiddenField hidCredit = (HiddenField)e.Row.FindControl("hidCredit");
                HiddenField hidBalance = (HiddenField)e.Row.FindControl("hidBalance");
                if (Math.Abs(Convert.ToDouble(hidDebit.Value)) == 0)
                {
                    lblDebit.Text = "";
                }
                else
                {
                    lblDebit.Text = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(hidDebit.Value)))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");
                }
                if (Math.Abs(Convert.ToDouble(hidCredit.Value)) == 0)
                {
                    lblCredit.Text = "";
                }
                else
                {
                    lblCredit.Text = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(hidCredit.Value)))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");
                }
                dblDebit += Convert.ToDouble(hidDebit.Value);
                dblCredit += Convert.ToDouble(hidCredit.Value);
                //***************End Display Format and get total ****//
            }

        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            string strOpeningDebit = string.Empty;
            string strOpeningCredit = string.Empty;
            string strDebit = string.Empty;
            string strCridit = string.Empty;
            string strClosingDebit = string.Empty;
            string strClosingCredit = string.Empty;
            
            //****************Opening Balance*******//
            double dblOpeningBalance = _GetOpeningBalance(ddlLedger.SelectedValue, txtFromDate.Text);
            if (dblOpeningBalance < 0)
            {
                strOpeningDebit = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(dblOpeningBalance)))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");
            }
            else if (dblDebit == 0)
            {
                strOpeningDebit = "";
            }
            if (dblOpeningBalance > 0)
            {
                strOpeningCredit = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(dblOpeningBalance)))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");

            }
            else if (dblDebit == 0)
            {
                strOpeningCredit = "";
            }
            //****************End Opening Balance*******//

            //*************Current Total***********//
            if (dblDebit < 0)
            {
                strDebit = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(dblDebit)))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");
            }
            else if (dblDebit == 0)
            {
                strDebit = "";
            }
            if (dblCredit > 0)
            {
                strCridit = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(dblCredit)))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");

            }
            else if (dblDebit == 0)
            {
                strCridit = "";
            }
            //***************End Current Total***********//
            //***************Closing Balance************//
            double dblClosingBalance = dblOpeningBalance + dblDebit + dblCredit;
            if (dblClosingBalance < 0)
            {
                strClosingDebit = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(dblClosingBalance)))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");
            }
            else if (dblClosingBalance > 0)
            {
                strClosingCredit = Convert.ToDouble(string.Format("{0:0.00}", Math.Abs(Convert.ToDouble(dblClosingBalance)))).ToString("c", new CultureInfo("hi-IN")).Replace("रु", "");
            }
            else
            {
                strClosingDebit = string.Empty;
                strClosingCredit = string.Empty;
            }
            //*****************End Clsing Balance************//
            //*****************Add Extra row in footer row**************//
            e.Row.Style.Add("background", "#ececec");
            //e.Row.Cells[0].Attributes.Add("rowspan", "3");
            e.Row.Cells[0].Style.Add("border", "none");
            //e.Row.Cells[1].Attributes.Add("rowspan", "3");
            e.Row.Cells[1].Style.Add("border", "none");
           // e.Row.Cells[1].Style.Add("border-right", "solid 0px #ececec");
            //e.Row.Cells[2].Attributes.Add("rowspan", "3");
            e.Row.Cells[2].Style.Add("border", "none");
            e.Row.Cells[3].Text = "Opening Balance";
            e.Row.Cells[3].Style.Add("font-weight", "bold");
            e.Row.Cells[3].Style.Add("border-left", "solid 1px #818181");
            e.Row.Cells[4].Text = strOpeningDebit;
            e.Row.Cells[4].Style.Add("text-align", "right");
            e.Row.Cells[4].Style.Add("font-weight", "bold");
            e.Row.Cells[5].Text = strOpeningCredit;
            e.Row.Cells[5].Style.Add("font-weight", "bold");
            e.Row.Cells[5].Style.Add("text-align", "right");
            string NewRow = "</td></tr><tr style=\"background:#ececec; font-weight:bold;\"><td style=\"border:none\">&nbsp;</td><td style=\"border:none\">&nbsp;</td><td style=\"border:none\">&nbsp;</td><td style=\"border-left:solid 1px #818181;\">Current Total</td><td style=\"text-align:right;\">" + strDebit.ToString() + "</td><td  style=\"text-align:right;\">" + strCridit.ToString() + "</td></tr>";
            NewRow += "<tr style=\"background:#ececec; font-weight:bold;\"><td style=\"border:none\">&nbsp;</td><td style=\"border:none\">&nbsp;</td><td style=\"border:none\">&nbsp;</td><td style=\"border-left:solid 1px #818181;\">Closing Balance</td><td  style=\"text-align:right;\">" + strClosingDebit.ToString() + "</td><td  style=\"text-align:right; \">" + strClosingCredit.ToString();
            e.Row.Cells[5].Text = e.Row.Cells[5].Text + " " + NewRow;
            //****************End Extra Row in footer row*************//
        }

    }
    private double _GetOpeningBalance(string strLID, string strDate)
    {
        double dblOpenBalance = 0;
        if (strLID != string.Empty && strDate != string.Empty)
        {
            string strIsFirstYear = string.Empty;
            strSql = "SELECT MIN(FINYEAR)AS FINYEAR FROM MAS_FINYEAR";
            DataTable DTMinFinyear = DU.getdata(strSql);
            if (DTMinFinyear.Rows.Count > 0)
            {
                if (Convert.ToInt32(DTMinFinyear.Rows[0]["FINYEAR"].ToString()) == Convert.ToInt32(Session["FINYEAR"].ToString()))
                {
                    strIsFirstYear = "1";
                }
                else
                {
                    strIsFirstYear = "0";
                }
            }
            string[] str = strDate.ToString().Split('/');
            strDate = str[1] + "/" + str[0] + "/" + str[2];
            SqlParameter[] sparam ={
                                       new SqlParameter("@LID",strLID),
                                       new SqlParameter("@DATE",strDate),
                                       new SqlParameter("@ISFIRSTYEAR",strIsFirstYear),
                                       new SqlParameter("@FINYEAR",Session["FINYEAR"].ToString())
                                   };
            DataTable DTOpenBal = DU.getdatausingprocedure("USP_ACC_GetLedgerOpeningBalance", sparam);
            if (DTOpenBal.Rows.Count > 0)
            {
                if (DTOpenBal.Rows[0]["OPENINGBALANCE"].ToString() != string.Empty)
                {
                    dblOpenBalance = Convert.ToDouble(DTOpenBal.Rows[0]["OPENINGBALANCE"].ToString());
                }
            }
        }
        return dblOpenBalance;
    }

    private void PrepareGridViewForExport(Control gv)
    {
        HiddenField hidControl = new HiddenField();       
        for (int i = 0; i < gv.Controls.Count; i++)
        {
            if (gv.Controls[i].GetType() == typeof(HiddenField))
            {               
                gv.Controls.Remove(gv.Controls[i]);                
            }            
            if (gv.Controls[i].HasControls())
            {
                PrepareGridViewForExport(gv.Controls[i]);
            }
        }
    }
    protected void btnPDF_Click(object sender, EventArgs e)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=GeneralLedger.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Document document = new Document(PageSize.A4, 80, 50, 30, 65);
        try
        {
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            PrepareGridViewForExport(grdDisplay);
            grdDisplay.RenderControl(htw);
            string strDataBody = "<html><head></head><body>" + htw.InnerWriter.ToString() + "</body></html>";
            iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();

            PdfWriter.GetInstance(document, Response.OutputStream);
            document.Open();
            ArrayList  objects;
            document.NewPage();
            Chunk c = new Chunk(Session["compname"].ToString() + "\n", FontFactory.GetFont("Verdana", 12));
            Paragraph p = new Paragraph();
            p.Alignment = Element.ALIGN_CENTER;
            p.Add(c);
            Chunk chunk1 = new Chunk(lblHeading.Text +"\n\n", FontFactory.GetFont("Verdana", 10));
            Paragraph p1 = new Paragraph();
            p1.Alignment = Element.ALIGN_LEFT;
            p1.Add(chunk1);

            document.Add(p);
            document.Add(p1);
            Paragraph p2 = new Paragraph();
            objects = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(strDataBody), styles);
            for (int k = 0; k < objects.Count; k++)
            {
                p2.Add((iTextSharp.text.IElement)objects[k]);
            }
            p2.Font = FontFactory.GetFont("Verdana", 7);
            document.Add(p2);
            document.Close();
            Response.Write(document);
            Response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected iTextSharp.text.Paragraph _GetDataForPDF(DataTable DT)
    {
        iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph();
        return p;
    }
}



